package com.atguigu.srb.gateway.filter;

import com.atguigu.srb.common.utils.JwtUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;

@Component
public class AuthFilter1 implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        RequestPath path = request.getPath();
        URI uri = request.getURI();

        Long userId = null;
        HttpHeaders headers = request.getHeaders();
        if(null!=headers&&headers.size()>0){
            List<String> tokens = headers.get("token");
            if(null!=tokens&&tokens.size()>0){
                String token = tokens.get(0);
                if(!StringUtils.isEmpty(token)){
                    boolean b = JwtUtils.checkToken(token);
                    if(b){
                        userId = JwtUtils.getUserId(token);
                        if (StringUtils.isEmpty(userId)){
                            System.out.println(userId);
                            request.mutate().header("userId",userId.toString());
                            exchange.mutate().request(request);
                        }
                    }
                }
            }
        }
        return chain.filter(exchange);
    }
}
